import { ref } from "vue";
import { Apis } from "@/apis";
export const useComments = (pageSize: number) => {
  const page = ref<number>(1);
  const comments = ref<any[]>([]);
  const total = ref<number>(0);
  const isLoaded = ref<boolean>(false);
  const postID = ref<number>(-1);
  const getComments = async (postId: number): Promise<any> => {
    postID.value = postId;
    console.log("getComments", postID.value, page.value, pageSize);
    const res = await Apis.getPostComments({
      page: page.value,
      pageSize,
      postId: postID.value,
    });
    if (!res.comments.length || res.comments.length < pageSize) {
      isLoaded.value = true;
    } else {
      isLoaded.value = false;
    }
    comments.value.push(...res.comments);
    total.value = res.total;
    return Promise.resolve();
  };
  const nextPage = (): void => {
    if (isLoaded.value) return;
    page.value++;
    getComments(postID.value);
  };
  const createComment = async (
    content: string,
    parentId: number | null
  ): Promise<any> => {
    await Apis.createComment({
      postId: postID.value,
      content,
      parentId,
    });
    return Promise.resolve();
  };
  const getChildrenComments = async (
    parentId: number,
    page: number,
    pageSize: number
  ): Promise<any> => {
    const res = await Apis.getChidrenComments({
      page,
      pageSize,
      parentId,
    });
    return Promise.resolve(res.data);
  };
  const refreshComment = async (): Promise<any> => {
    page.value = 1;
    comments.value = [];
    total.value = 0;
    await getComments(postID.value);
    return Promise.resolve();
  };
  const clearComments = (): void => {
    comments.value = [];
    total.value = 0;
    page.value = 1;
    postID.value = -1;
  };
  return {
    comments,
    total,
    page,
    isLoaded,
    nextPage,
    getComments,
    getChildrenComments,
    createComment,
    refreshComment,
    clearComments,
  };
};
